<template>
  <div id="indexApp">
    <mx-header> 电子工卡 </mx-header>
    <div class="content" ref="homeScroll">
      <div class="bg-whithe-view">
        <div class="board-line-view">
          <!-- 公司信息 -->
          <img class="logoIcon" src="../../assets/img/Combined_Shape.png" alt="logo"/>
          <img class="userAvatar" :src="avatar" @error="loadUserAvatarError"/>
          <div class="userName">{{ userInfo.cn }}</div>
          <div class="userNamePY">{{ userInfo.cn ? convertToPinyin(userInfo.cn) : '' }}</div>
          <div class="cardNo">{{ 'NO.' + userInfo.uid }}</div>
          <img class="BOElogo" src="../../assets/img/BOElogo.png" alt="logo"/>
          <!-- 核酸状态 - 未上传 -->
          <!-- <div v-if="!upLoadPictureState" class="gray-Line">
            <div class="line-text">核酸</div>
            <div class="upload-view">
              <button class="upLoadBtn" @click="choosePictureAndupLoad">
                上传核酸证明
              </button>
              <img class="heicon-bg" src="../../assets/img/question_icon@2x.png" alt="问号" @click="handleShowAlert"/>
            </div>
          </div> -->
          <!-- 核酸状态 - 已上传 -->
          <div v-if="upLoadPictureState" class="gray-Line">
            <div class="line-text">核酸</div>
            <div class="resultText">{{ hsResult }}</div>
            <div class="hsShowTime">时间<span class="timeResult">{{ hsTime }}</span>天</div>
          </div>
          <!-- 疫苗状态 -->
          <div v-if="upLoadPictureState" class="gray-Line">
            <div class="line-text">疫苗</div>
            <div class="resultText">{{ ymResult }}</div>
          </div>
          <!-- 二维码状态 -->
          <div class="qrCode-bgview">
            <button class="qrCode-button" @click="gotoQrCodeView">二维码</button>
          </div>
          <!-- 时间 -->
          <div class="date">当前时间：{{ date }}</div>
          <!-- 二维码弹窗 -->
          <div class="qrcode-bg" v-if="showPopup" @click.stop="showPopup=false">
            <div class="qrcode">
              <vue-qr
                class="qrCode-img"
                :logoSrc="qrcodeLogo"
                :text="qrCodeImg"
                :margin="10"
                :size="200">
              </vue-qr>
              <p  class="qrCode-date">{{ date }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import Pinyin from 'js-pinyin'
import VueQr from 'vue-qr'
import Native from '@/service/native'
import { McWidgetIdentifier } from '../../config/main.js'
import MxHeader from '../../components/mx-header'
// import { getTencentOcrApi } from '@/service/http/api/tencentOcr'
import { httpDispatch } from '@/service/http'
import { base64Data } from '../../config/pictureTest'
import { getUserCardUrl } from '../../utils'

export default {
  data() {
    return {
      defaultCardIcon: require('../../assets/img/defaultUserHeader.jpg'),
      qrcodeLogo: require('../../assets/img/qrcode_logo.jpg'),
      userInfo: {},
      avatar: '',
      hsResult: '',
      hsTime: '',
      ymResult: '',
      upLoadPictureState: false,
      date: '',
      timer: null,
      showPopup: false,
      qrCodeImg: ''
    }
  },
  components: {
    MxHeader,
    VueQr
  },
  mounted() {
    // 用户信息
    this.userInfo = this.userData
    const { uid, cn } = this.userInfo
    // 用户头像
    this.avatar = getUserCardUrl(uid)
    // 水印
    const watermarkTime = new Date().toLocaleDateString()
    this.$watermark.set(`${cn}(${uid}) ${watermarkTime}`)

    // 时间定时器
    this.timer = window.setInterval(() => {
      this.date = new Date().toLocaleString()
    }, 1000)
  },
  computed: {
    ...mapGetters('userStore', ['userData'])
  },
  methods: {
    // 获取用户头像失败 - 没有头像
    loadUserAvatarError() {
      this.avatar = this.defaultCardIcon
    },

    // 用户信息处理，把姓名按特定规则转成拼音
    convertToPinyin(sourceStr) {
      let firstCN = sourceStr.substr(0, 1)

      // 非中文
      const reg = /[\u4e00-\u9fa5]+/g
      if (!firstCN.match(reg)) return sourceStr

      // 中文
      let firstEn = Pinyin.getFullChars(firstCN)
      let other = Pinyin.getCamelChars(sourceStr.substr(1))
      let ls = other.split('')
      let otherStr = ls.join('.')
      return otherStr + '.' + firstEn
    },

    // 问号提示弹窗
    handleShowAlert() {
      this.alertTheQuestion('请上传健康宝-本人健康码自查询截图')
    },

    // 点击进行温馨提示弹框
    alertTheQuestion(msg) {
      this.$layer
        .dialog({
          // title: [], // 第一个是标题内容  第二个是标题栏的style(可以为空)
          content: msg,
          contentClass: 'className',
          btn: ['确定']
          //   time: 2000
        })
        // 如果有btn
        .then(function (res) {
          // res为0时是用户点击了左边  为1时用户点击了右边
          let position = res === 0 ? 'left' : 'right'
        })
    },

    // 点击生成二维码
    gotoQrCodeView() {
      this.$mxLoading.show()
      this.createQrCode()
    },

    // 上传核算证明，打开手机相册
    async choosePictureAndupLoad() {
      // 本地pc测试
      let base64Url = base64Data

      // 测试、线上环境部署
      if (process.env.NODE_ENV !== 'development') {
        let res = await Native.api.getPictureByAlbum(1, 0)
        base64Url = res[0].base64Url
      }

      this.getOcr(base64Url)
    },

    // 调用 阿里云\腾讯 Ocr
    async getOcr (image) {
      try {
        const data = await httpDispatch('mas-card-ocr', {
          data: { image },
          param: { image }
        });

        this.handleOcrText(data)
      } catch (error) {
        console.log(error)
        this.$toast('识别失败请稍后再试')
      }
    },

    // 处理腾讯 Ocr 校验结果
    handleOcrText(wordsResult) {
      const { testingResult, testingInterval, vaccination, time = '' } = wordsResult
      const testingIntervalRes = testingInterval.length ? testingInterval.slice(0, 1) : 0

      this.hsResult = testingResult
      this.hsTime = testingIntervalRes
      this.ymResult = vaccination

      // 上传时间校验
      let updateTime = time.substring(0, 10).replace(/\D/ig, '-')
      const updateTimeStamp = new Date(updateTime).getTime()

      // 获取当前是几号
      const today = new Date()
      let nowMonth = today.getMonth() + 1
      let strDate = today.getDate()

      // 对月份进行处理，1-9月在前面添加一个“0”
      if (nowMonth >= 1 && nowMonth <= 9) {
        nowMonth = `0${nowMonth}`
      }

      // 对月份进行处理，1-9号在前面添加一个“0”
      if (strDate >= 0 && strDate <= 9) {
        strDate = `0${strDate}`
      }

      // 最后拼接字符串，得到一个格式为(yyyy-MM-dd)的日期
      const todayDateString = `${today.getFullYear()}-${nowMonth}-${strDate}`
      const todayTimeStamp = new Date(todayDateString.replace(/\D/ig, '-')).getTime()

      if (todayTimeStamp === updateTimeStamp) {
        this.upLoadPictureState = true
      } else {
        this.alertTheQuestion('上传健康宝截图日期须与当前日期一致，请重新上传')
        this.upLoadPictureState = false
      }
    },

    // 创建二维码
    async createQrCode() {
      if (this.qrCodeImg) {
        this.showPopup = true
        this.$mxLoading.hide()
        return
      }

      const urlParam = {
        target: `${McWidgetIdentifier}`,
        action: 'scan_open_h5',
        param: {
          name: this.userInfo.cn,
          uid: this.userInfo.uid,
          dept: this.userInfo.dept,
          mobile: this.userInfo.mobile,
          source: 'mobileportal',
          action: 'qrCodeInfo'
        }
      }

      this.qrCodeImg = JSON.stringify(urlParam)
      this.showPopup = true
      this.$mxLoading.hide()
    }
  }
}
</script>

<style lang="less" scoped>
.content {
  background: gray;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: 'PingFang SC','Microsoft YaHei', 'SimHei';
}
.bg-whithe-view {
  width: 3.42rem;
  background-color: white;
  border-radius: 0.34rem;
  .board-line-view {
    border-radius: 0.3rem;
    margin: 0.27rem;
    padding: 0 .2rem;
    text-align: center;
    border: 1px solid rgba(151, 151, 151, 45%);

    .logoIcon {
      width: 1.1rem;
      display: block;
      margin: 0.3rem auto 0.25rem;
    }

    // 公司信息
    .userAvatar {
      height: 1.94rem;
      width: 1.94rem;
      display: block;
      margin: 0.1rem auto 0;
      object-fit: contain;
    }
    .userName {
      margin-top: 0.15rem;
      font-size: 0.2rem;
      font-weight: bold;
      color: #4A4A4A;;
    }
    .userNamePY {
      font-size: 0.14rem;
      font-weight: bold;
      color: #000;
    }
    .cardNo {
      font-size: 0.14rem;
      color: #9B9B9B;
    }
    .BOElogo {
      width: 1.9rem;
      height: auto;
      margin: .19rem auto .05rem;
    }

    // 核酸信息
    .gray-Line {
      background-color: rgba(216, 216, 216, 0.36);
      width: 100%;
      display: flow-root;
      height: 0.3rem;
      line-height: 0.3rem;
      font-size: 0.14rem;
      margin-top: 0.04rem;
    }
    .line-text {
      width: 30%;
      color: #4a4a4a;
      font-size: 0.15rem;
      float: left;
      vertical-align: middle;
      line-height: 0.3rem;
    }
    .hsShowTime {
      width: 30%;
      float: left;
      height: 100%;
      vertical-align: middle;
      line-height: 0.3rem;
      font-size: .13rem;
      .timeResult {
        color: #50e3c2;
        font-size: 0.22rem;
        margin: 0 0.02rem;
      }
    }
    .upload-view {
      height: 100%;
      text-align: center;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 0.16rem;
      .upLoadBtn {
        color: #4a90e2;
        height: 0.2rem;
        line-height: 0.2rem;
        margin-top: 0.02rem;
        border: none;
        border-radius: 12rem;
        font-size: 0.12rem;
        background: rgba(0,94,186,0.07);
      }
      .heicon-bg {
        width: 0.2rem;
        height: 0.2rem;
      }
    }
    .resultText {
      width: 40%;
      float: left;
      vertical-align: middle;
      text-align: center;
      height: 0.3rem;
      line-height: 0.3rem;
      color: #50e3c2;
      font-size: .17rem;
      word-break: keep-all;
    }
  }

  .qrCode-bgview {
    vertical-align: bottom;
  }
  .qrCode-button {
    margin: 0.15rem auto 0.15rem;
    width: 0.8rem;
    height: 0.3rem;
    background-color: #005eba;
    border-radius: 0.13rem;
    border: none;
    color: white;
    vertical-align: middle;
  }
  .date {
    margin-bottom: 0.1rem;
    font-size: 0.12rem;
    color: #4a4a4a;
  }
  .qrcode-bg {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,.6);
      display: flex;
      justify-content: center;
      align-items: center;

    .qrcode {
      width: 2.7rem;
      height: 2.7rem;
      display: flex;
      background: url(../../assets/img/qrcode-bgview.png) center center;
      background-size: 100%;
      background-repeat: no-repeat;
      border-radius: 0.1rem;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .qrCode-img {
        width: 1.88rem;
        height: 1.88rem;
        background: #fff;
        padding: 0.2rem;
        padding-bottom: 0;
        margin-bottom: -.05rem;
        border-top-left-radius: .2rem;
        border-top-right-radius: .2rem;
      }
      .qrCode-date {
        background: #fff;
        width: 2.28rem;
        border-bottom-left-radius: .2rem;
        border-bottom-right-radius: .2rem;
        padding-bottom: 0.1rem;
        font-size: 0.12rem;
      }
    }
  }
}
</style>
